在spring boot中为静态资源设置setCachePeriod | 您所在的位置:网站首页 › java 静态资源 › 在spring boot中为静态资源设置setCachePeriod |
百度翻译此文
有道翻译此文
问题描述
I am using spring boot, and the /static is served as static resources like js and css, so far so good, while I want to set the cache header of these files, so I tried this: @Configuration public class BaseMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/").setCachePeriod(24 * 3600 * 365); } }However after that, the application can not serve anything from the /static folder. What's the problem? 推荐答案In my opinion, it's better to use spring.resources.cache-period property to set the cache period of default Boot Resource Handler. So add the following to your application.properties: spring.resources.cache-period = 31536000And delete the BaseMvcConfig config file. 其他推荐答案Since spring.resources.cache-period is deprecated, you may want to use the newer spring.web.resources.cache.period instead, which takes either seconds (as before), or a Duration specification like this: spring.web.resources.cache.period = P30DSee Duration#parse() JavaDoc for reference. 其他推荐答案If you want to use spring security for controllers and setup cache for static content then you might want to configure exceptions in your WebSecurityConfigurerAdapter and set cache period in application.properties: @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/js/**", "/css/**"); } #1 week cache spring.resources.cache-period = 604800 |
CopyRight 2018-2019 实验室设备网 版权所有 |